package com.leyou.sms.listeners;

import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Component
public class Listener {

    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "SmsQueue", durable = "true"),
            exchange = @Exchange(name = "lySMS", type = ExchangeTypes.TOPIC),
            key = "codeSms"))
    public void listenVerifyCodeMessage(Map<String, String> msg) {

        if (CollectionUtils.isEmpty(msg)) {
            throw new LyException("消息为空", 400);
        }

        //效验手机号
        String phone = msg.get("phone");
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException("手机号码规格有误", 400);
        }
        //效验验证码
        String code = msg.get("code");
        if (!RegexUtils.isCodeValid(code)) {
            throw new LyException("验证码格式错误", 400);

        }

        //发送短信
        try {
            smsUtils.sendVerifyCode(phone, code);
            System.out.println("短信发送成功");
        } catch (Exception e) {
            throw new LyException("短信发送失败",400);
        }
    }
}
